<script lang="ts" setup>
import { ElMessage, ElTable } from 'element-plus'
import { reactive, ref } from 'vue'
import * as XLSX from 'xlsx'
import dayjs from 'dayjs'
import qs from 'qs'
import { GetSkincheckList } from '@/api/modules/skincheck'
import GetCacheData from '@/store/modules/NewPageCache'

const cacheData = GetCacheData()
const router = useRouter()
let PageNum = cacheData.GetCacheData('skincheck').currentPage
const loading = ref(false)
const total = ref(0) // 总数据数

// 数据列表
const dataList = reactive({
  list: [],
})

// 查询表单
const findFrom = ref({
  ...(cacheData.GetCacheData('skincheck').fromData),
})

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('skincheck').currentSize)
  cacheData.SetCacheData('skincheck', PageNum, cacheData.GetCacheData('skincheck').currentSize, findFrom.value)
}

// 获取商品业绩数据
async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = qs.stringify({
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.Source && ({ Source: findFrom.value.Source })),
    ...(findFrom.value.ExcludeUserIds && ({ ExcludeUserIds: findFrom.value.ExcludeUserIds.split(/[,，]/).map(Number).filter((id: number) => id !== 0) })),
    ...(findFrom.value.ChannelId !== '~' && ({ ChannelId: findFrom.value.ChannelId })),
    ...(findFrom.value.RecStatus !== '~' && ({ RecStatus: findFrom.value.RecStatus })),
    ...(findFrom.value.AddTIme?.length > 0 && {
      StartAddTime: findFrom.value.AddTIme[0],
      EndAddTime: findFrom.value.AddTIme[1],
    }),
  })

  await GetSkincheckList(params).then((res: any) => {
    // console.log(res.data.items)
    if (res.succeeded) {
      dataList.list = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
      loading.value = false
    }
  }).catch(() => {
    ElMessage.error('获取数据失败。')
    loading.value = false
  })
}

async function ExportExcel() {
  const params = {
    PageIndex: 1,
    PageSize: 1000,
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.Source && ({ Source: findFrom.value.Source })),
    ...(findFrom.value.ExcludeUserIds && ({ ExcludeUserIds: findFrom.value.ExcludeUserIds.split(/[,，]/).map(Number).filter((id: number) => id !== 0) })),
    ...(findFrom.value.RecStatus !== '~' && ({ RecStatus: findFrom.value.RecStatus })),
    ...(findFrom.value.AddTIme?.length > 0 && {
      StartAddTime: findFrom.value.AddTIme[0],
      EndAddTime: findFrom.value.AddTIme[1],
    }),
  }

  const excelData = await GetSkincheckList(params)

  const headerMapping = {
    id: '测肤记录ID',
    userId: '用户ID',
    scOpenId: '用户OpenId',
    UnionId: '用户UnionId',
    userNickName: '用户昵称',
    userPhone: '授权手机号',
    age: '肤龄',
    skinColorType: '肤色',
    skinTypeNum: '肤质',
    totalScore: '总得分',
    skinColorScore: '肤色打分',
    wrinkleScore: '皱纹打分',
    waterScore: '水分打分',
    acneScore: '痔疮打分',
    poreScore: '毛孔打分',
    darkEyeCircleScore: '黑眼圈打分',
    blackHeadsScore: '黑头打分',
    splashScore: '色斑打分',
    addTime: '添加时间',
  } as { [key: string]: string }

  // console.log(excelData.data)skinTypeNum

  // 映射数据和合并order对象
  const newData = excelData.data.items.map((item: { [key: string]: any }) => {
    // 解构用户信息
    item.userId = item.subscriber?.userId
    item.scOpenId = item.subscriber?.scOpenId
    item.UnionId = item.subscriber?.UnionId
    item.userNickName = item.subscriber?.userNickName
    item.userPhone = item.subscriber?.userPhone

    delete item.subscriber

    const skinColorTypeObj = {
      17: '透白',
      34: '白皙',
      51: '自然',
      68: '小麦',
      85: '暗沉',
      0: '暗沉',
    } as { [key: string]: string }
    item.skinColorType = skinColorTypeObj[item.skinColorType]
    const skinTypeNumObj = {
      17: '油性肤质',
      34: '干性肤质',
      51: '混合肤质',
      0: '中性肤质',
    } as { [key: string]: string }
    item.skinTypeNum = skinTypeNumObj[item.skinTypeNum]

    return Object.keys(item).reduce((newItem, key) => {
      (newItem as { [key: string]: any })[headerMapping[key] || key] = item[key]
      return newItem
    }, {})
  })
  // console.log(newData)

  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(newData)
  // 设置列宽
  ws['!cols'] = [{ wch: 10 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 30 }, { wch: 20 }, { wch: 20 }, { wch: 15 }, { wch: 15 }, { wch: 30 }]
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, `测肤记录_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`)
}

const shortcuts = [
  {
    text: '今天',
    value: () => {
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: '近一周',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '近一月',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '近一年',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date()
      start.setFullYear(start.getFullYear() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
]

function SetPage(pageKey: string, SkinCheckId: number) {
  router.push({
    name: pageKey,
    query: {
      SkinCheckId,
    },
  })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('skincheck', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('skincheck').currentSize)
  cacheData.SetCacheData('skincheck', val, cacheData.GetCacheData('skincheck').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('skincheck').currentPage || 1
})

onMounted(() => {
  GetDataList(cacheData.GetCacheData('skincheck').currentPage, cacheData.GetCacheData('skincheck').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="授权手机号">
                <el-input v-model="findFrom.UserPhone" placeholder="请输入授权手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="评测时间">
                <el-date-picker
                  v-model="findFrom.AddTIme" type="daterange" clearable value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
                  :shortcuts="shortcuts"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.RecStatus" placeholder="请选择渠道">
                  <el-option label="全部" value="~" />
                  <el-option label="正常" :value="1" />
                  <el-option label="删除" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="排除用户ID">
                <el-input v-model="findFrom.ExcludeUserIds" placeholder="请输入排除用户ID（逗号分隔）" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="获客来源">
                <el-input v-model="findFrom.Source" placeholder="请输入获客来源" clearable @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出
        </el-button>
      </div>
      <ElTable v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="测肤记录ID" width="100" />
        <el-table-column align="center" prop="subscriber.userId" label="用户Id" width="100" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriber">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.subscriber?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.subscriber?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.subscriber?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="source" label="获客来源" width="140" />
        <el-table-column align="center" prop="photoUrl" label="测肤照片" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="scope.row.photoUrl" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="age" label="肤龄" width="100" />
        <el-table-column align="center" prop="skinColorType" label="肤色" width="120">
          <template #default="scope">
            <el-tag>
              {{ scope.row.skinColorType === 17 ? '透白'
                : scope.row.skinColorType === 34 ? '白皙'
                  : scope.row.skinColorType === 51 ? '自然'
                    : scope.row.skinColorType === 68 ? '小麦'
                      : scope.row.skinColorType === 85 ? '暗沉'
                        : scope.row.skinColorType === 0 ? '黝黑' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="skinColorType" label="肤质" width="120">
          <template #default="scope">
            <el-tag>
              {{ scope.row.skinTypeNum === 17 ? '油性肤质'
                : scope.row.skinTypeNum === 34 ? '干性肤质'
                  : scope.row.skinTypeNum === 51 ? '混合肤质'
                    : scope.row.skinTypeNum === 0 ? '中性肤质' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="totalScore" label="总得分" width="140" />
        <el-table-column align="center" prop="skinColorScore" label="肤色打分" width="140" />
        <el-table-column align="center" prop="wrinkleScore" label="皱纹打分" width="140" />
        <el-table-column align="center" prop="waterScore" label="水分打分" width="140" />
        <el-table-column align="center" prop="acneScore" label="痤疮打分" width="140" />
        <el-table-column align="center" prop="poreScore" label="毛孔打分" width="140" />
        <el-table-column align="center" prop="darkEyeCircleScore" label="黑眼圈打分" width="140" />
        <el-table-column align="center" prop="blackHeadsScore" label="黑头打分" width="140" />
        <el-table-column align="center" prop="splashScore" label="色斑打分" width="140" />
        <el-table-column align="center" prop="addTime" label="添加时间" min-width="240" />
        <el-table-column align="center" prop="recStatus" label="状态" fixed="right" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.recStatus === 1 ? 'primary' : 'danger'">
              {{ scope.row.recStatus === 1 ? '正常'
                : scope.row.recStatus === 2 ? '删除' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="150">
          <template #default="scope">
            <el-button type="primary" @click="SetPage('skincheckTicketSentList', scope.row.id)">
              发券记录
            </el-button>
          </template>
        </el-table-column>
      </ElTable>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('pintuan').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
